//手写promise：

// class Promise {
//     constructor(fn) {
//         this.status = 'penging';
//         this.resolve = undefined;
//         this.reject = undefined;
//         let resolve = (value) => {
//             if (this.status == 'penging') {
//                 this.status = resolve;
//                 this.resolve = value;
//             }
//         }
//         let reject = (err) => {
//             if (this.status == 'penging') {
//                 this.status = reject;
//                 this.reject = err;
//             }
//         }
//         try {
//             fn(resolve, reject)
//         } catch (err) {
//             reject(err)
//         }
//     }
//     then(onRes, onRej) {
//         switch (this.status) {
//             case 'resolve':
//                 setTimeout(function() {
//                     onRes(this.resolve);
//                 })

//                 break;
//             case 'reject':
//                 setTimeout(function() {
//                     onRes(this.reject);
//                 })

//                 break;
//             default:
//         }
//     }
// }

// 手写 Promise.all

function myPromiseAll(promiseAll) {
    return new Promise((resolve, reject) => {
        if (!Array.isArray(promiseAll)) {
            throw 'promise must be an Array'
        }
        let resArr = [];
        let len = promiseAll.length;
        let count = 0;
        for (let i = 0; i < len; i++) {
            Promise.resolve(promiseAll[i]).then((value) => {
                resArr[i] = value;
                count++;
                if (count == len) {
                    resolve(resArr);
                }
            }).catch((err) => {
                reject(err);
            })
        }
    })
}

let p1 = Promise.resolve(1);
let p2 = Promise.resolve(2);
let p3 = Promise.resolve(3);
myPromiseAll([p1, p3, p2]).then((res) => {
    console.log(res);

})


// 手写 Promise.race
function myPromiseRace(promiseRace) {
    return new Promise((resolve, reject) => {
        if (!Array.isArray(promiseRace)) {
            throw 'promiseRace must be a array'
        }
        for (let i = 0; i < promiseRace.length; i++) {
            Promise.resolve(promiseRace[i]).then((res) => {
                resolve(res)
            }).catch((err) => {
                reject(err)
            })
        }
    })
}

let p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject(1)
    }, 50)
})
let p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject(22)
    }, 10)
})
let p3 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(3)
    }, 20)
})
myPromiseRace([p2, p3, p1])
    .then(res => console.log(res))
    .catch(err => console.log(err)) // 1